

#import "FAMCameFoodResultViewController.h"
#import "FAMCameFoodResultCollectionViewCell.h"
#import "FAMCameLoadingView.h"
@interface FAMCameFoodResultViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *FAMAdjustmentButton;
@property (weak, nonatomic) IBOutlet UIImageView *FAMSelectedImageView;
@property (weak, nonatomic) IBOutlet UILabel *FAMFoodNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *FAMDetailLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *FAMNutrientCollectionView;
@property (weak, nonatomic) IBOutlet UICollectionView *FAMTotalCollectionView;
@property (weak, nonatomic) IBOutlet UIScrollView *FAMScrollView;
@property (nonatomic, strong)NSMutableArray *FAMNutrientArray,*FAMTotalArray;

@property (weak, nonatomic) IBOutlet UIView *FAMMealsBackView;
@property (weak, nonatomic) IBOutlet UIImageView *FAMMealsImageView;

@property (nonatomic, assign)bool FAMIsMeals;
@property (weak, nonatomic) IBOutlet UIView *FAMMealsView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *FAMFAMNutrientCollectionViewHeight;


@property (weak, nonatomic) IBOutlet UILabel *FAMMealtimeLabel;

@property (weak, nonatomic) IBOutlet UIButton *FAMMealOneButton;
@property (weak, nonatomic) IBOutlet UIButton *FAMMealTwoButton;
@property (weak, nonatomic) IBOutlet UIButton *FAMMealThreeButton;
@end

@implementation FAMCameFoodResultViewController
- (NSMutableArray *)FAMNutrientArray{
    if (!_FAMNutrientArray) {
        _FAMNutrientArray = [NSMutableArray array];
    }
    return _FAMNutrientArray;
}
- (NSMutableArray *)FAMTotalArray{
    if (!_FAMTotalArray) {
        _FAMTotalArray = [NSMutableArray array];
    }
    return _FAMTotalArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_interactivePopDisabled = YES;
    [self FAM_loadData:self.FAMFoodModel];
    [self FAM_showUi];
    NSInteger hh = [FAMTool FAM_getCurrentHH];
    if ([self.FAMCateType isEqualToString:@"0"]){
        if (hh>=5 && hh<11) {
            self.FAMCateType = @"1";
        }else if (hh>=11 && hh<16){
            self.FAMCateType = @"2";
        }else if (hh>=16 && hh< 21){
            self.FAMCateType = @"3";
        }else{
            self.FAMCateType = @"4";
        }
    }
    if (hh>=5 && hh<11) {
        self.FAMMealtimeLabel.text = @"Breakfast";
        [self.FAMMealOneButton setTitle:@"Lunch" forState:UIControlStateNormal];
        [self.FAMMealTwoButton setTitle:@"Dinner" forState:UIControlStateNormal];
        [self.FAMMealThreeButton setTitle:@"Snacks" forState:UIControlStateNormal];
    }else if (hh>=11 && hh<16){
        self.FAMMealtimeLabel.text = @"Lunch";
        [self.FAMMealOneButton setTitle:@"Breakfast" forState:UIControlStateNormal];
        [self.FAMMealTwoButton setTitle:@"Dinner" forState:UIControlStateNormal];
        [self.FAMMealThreeButton setTitle:@"Snacks" forState:UIControlStateNormal];
    }else if (hh>=16 && hh< 21){
        self.FAMMealtimeLabel.text = @"Dinner";
        [self.FAMMealOneButton setTitle:@"Breakfast" forState:UIControlStateNormal];
        [self.FAMMealTwoButton setTitle:@"Lunch" forState:UIControlStateNormal];
        [self.FAMMealThreeButton setTitle:@"Snacks" forState:UIControlStateNormal];
    }else{
        self.FAMMealtimeLabel.text = @"Snacks";
        [self.FAMMealOneButton setTitle:@"Breakfast" forState:UIControlStateNormal];
        [self.FAMMealTwoButton setTitle:@"Lunch" forState:UIControlStateNormal];
        [self.FAMMealThreeButton setTitle:@"Dinner" forState:UIControlStateNormal];
    }
}
- (void)FAM_loadData:(FAMFoodIdentifyModel *)FAMFoodModel{
    [self.FAMNutrientArray removeAllObjects];
    [self.FAMTotalArray removeAllObjects];
    for (int i = 0; i<FAMFoodModel.foodList.count; i++) {
        FAMFoodIdentifyModel *model = FAMFoodModel.foodList[i];
        [self.FAMNutrientArray addObject:[NSString nullToString:model.food_name]];
        [self.FAMNutrientArray addObject:[NSString stringWithFormat:@"%@g",[[NSString nullToString:model.weight] isEqualToString:@""] == YES ? @"0" : model.weight]];
        [self.FAMNutrientArray addObject:[NSString stringWithFormat:@"%@kcal",[[NSString nullToString:model.calories] isEqualToString:@""] == YES ? @"0" : model.calories]];
    }
    if (self.FAMNutrientArray.count > 0) {
        self.FAMFoodNameLabel.text = self.FAMNutrientArray.firstObject;
        
//        self.FAMDetailLabel.text =
    }
    
    CGFloat Protein = 0;
    CGFloat Fat = 0;
    CGFloat Carbs = 0;
    CGFloat Calories = 0;
    for (int i = 0; i<FAMFoodModel.foodList.count; i++) {
        FAMFoodIdentifyModel *model = FAMFoodModel.foodList[i];
        Protein += model.protein.floatValue;
        Fat += model.fat.floatValue;
        Carbs += model.carbs.floatValue;
        Calories += model.calories.floatValue;
    }
    [self.FAMTotalArray addObject:@"Calories"];
    [self.FAMTotalArray addObject:[NSString stringWithFormat:@"%0.1f",Calories]];
    [self.FAMTotalArray addObject:@"Carbs"];
    [self.FAMTotalArray addObject:[NSString stringWithFormat:@"%0.1f",Carbs]];
    [self.FAMTotalArray addObject:@"Protein"];
    [self.FAMTotalArray addObject:[NSString stringWithFormat:@"%0.1f",Protein]];
    [self.FAMTotalArray addObject:@"Fat"];
    [self.FAMTotalArray addObject:[NSString stringWithFormat:@"%0.1f",Fat]];
    NSInteger divisor = self.FAMNutrientArray.count / 3 + 1;
    self.FAMFAMNutrientCollectionViewHeight.constant = divisor*45;
    [self.FAMNutrientCollectionView reloadData];
    [self.FAMTotalCollectionView reloadData];
    self.FAMFoodModel = FAMFoodModel;
}
- (void)FAM_showUi{
    self.FAMSelectedImageView.image = self.FAMSelectedImage;
    self.FAMAdjustmentButton.layer.borderWidth = 1;
    self.FAMAdjustmentButton.layer.borderColor = kCustom0xColor(0x191919, 1.0).CGColor;
    self.FAMScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.FAMNutrientCollectionView registerNib:[UINib nibWithNibName:@"FAMCameFoodResultCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    [self.FAMTotalCollectionView registerNib:[UINib nibWithNibName:@"FAMCameFoodResultCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    self.FAMNutrientCollectionView.scrollEnabled = NO;
    self.FAMTotalCollectionView.scrollEnabled = NO;
    
    
//    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    backButton.frame = CGRectMake(0, 0, 44, 44);
//    [backButton setImage:[UIImage imageNamed:@"general_back"] forState:UIControlStateNormal];
//    [backButton setImage:[UIImage imageNamed:@"general_back"] forState:UIControlStateSelected];
//    [backButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
//    [backButton addTarget:self action:@selector(FAM_backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backButton];
    self.FAMMealsBackView.layer.borderColor = kBlackColor.CGColor;
    self.FAMMealsBackView.layer.borderWidth = 1;
}

//- (void)FAM_backButtonClick:(UIButton *)sender{
//    NSArray *vcArray = self.navigationController.viewControllers;
//    [self.navigationController popToViewController:vcArray[1] animated:YES];
//}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.FAMNutrientCollectionView) {
        return 3 + self.FAMNutrientArray.count;
    }else{
        return 2 + self.FAMTotalArray.count;
    }
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.FAMNutrientCollectionView){
        FAMCameFoodResultCollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        if (indexPath.row < 3) {
            if (indexPath.row == 0) {
                cell.FAMTitle = @"Name";
            }else if (indexPath.row == 1){
                cell.FAMTitle = @"Weight";
            }else{
                cell.FAMTitle = @"Kcal";
            }
            cell.FAMBackColor = kCustom0xColor(0x191919, 1.0);
            cell.FAMTitleColor = kWhiteColor;
        }else{
            cell.FAMTitle = self.FAMNutrientArray[indexPath.row-3];
            cell.FAMBackColor = kCustom0xColor(0xF7F8F9, 1.0);
            cell.FAMTitleColor = kCustom0xColor(0x191919, 1.0);
        }
        
        return cell;
    }else{
        FAMCameFoodResultCollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        if (indexPath.row < 2) {
            if (indexPath.row == 1) {
                cell.FAMTitle = @"Nutrients";
            }else if (indexPath.row == 2){
                cell.FAMTitle = @"Total";
            }
            cell.FAMBackColor = kCustom0xColor(0xF7A912, 1.0);
            cell.FAMTitleColor = kWhiteColor;
        }else{
            cell.FAMTitle = self.FAMTotalArray[indexPath.row - 2];
            cell.FAMBackColor = kCustom0xColor(0xFFF6E3, 1.0);
            cell.FAMTitleColor = kCustom0xColor(0x191919, 1.0);
        }
        return cell;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 1;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 1;
}
-(CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath*)indexPath {
    if (collectionView == self.FAMNutrientCollectionView) {
        CGFloat cellWidth=(SCREEN_WIDTH-33)/3;
        return CGSizeMake(cellWidth,45);
    }else{
        CGFloat cellWidth=(SCREEN_WIDTH-31)/2;
        return CGSizeMake(cellWidth,45);
    }
}
- (IBAction)FAM_adjustMentButtonClick:(UIButton *)sender {
    FAMCameAdjustmentView *cameAdjustmentView = [[FAMCameAdjustmentView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    cameAdjustmentView.FAMFoodModel = self.FAMFoodModel;
    
    [self.view addSubview:cameAdjustmentView];
}

- (IBAction)FAM_mealsTapClick:(UITapGestureRecognizer *)sender {
    self.FAMIsMeals = !self.FAMIsMeals;
    if (self.FAMIsMeals) {
        self.FAMMealsImageView.image = [UIImage imageNamed:@"camera_up"];
        [self.FAMMealsView setHidden:NO];
    }else{
        self.FAMMealsImageView.image = [UIImage imageNamed:@"camera_down"];
        [self.FAMMealsView setHidden:YES];
    }
}

- (IBAction)FAM_mealOneButtonClick:(UIButton *)sender {
    [self FAM_setMeal:sender];
}
- (IBAction)FAM_mealTwoButtonClick:(UIButton *)sender {
    [self FAM_setMeal:sender];
}
- (IBAction)FAM_mealThreeButtonClick:(UIButton *)sender {
    [self FAM_setMeal:sender];
}
- (void)FAM_setMeal:(UIButton *)sender{
    NSString *tempString = self.FAMMealtimeLabel.text;
    self.FAMMealtimeLabel.text = sender.titleLabel.text;
    [sender setTitle:tempString forState:UIControlStateNormal];
    if ([self.FAMMealtimeLabel.text isEqualToString:@"Breakfast"]) {
        self.FAMCateType = @"1";
    }else if ([self.FAMMealtimeLabel.text isEqualToString:@"Lunch"]){
        self.FAMCateType = @"2";
    }else if ([self.FAMMealtimeLabel.text isEqualToString:@"Dinner"]){
        self.FAMCateType = @"3";
    }else{
        self.FAMCateType = @"4";
    }
    self.FAMIsMeals = !self.FAMIsMeals;
    self.FAMMealsImageView.image = [UIImage imageNamed:@"camera_down"];
    [self.FAMMealsView setHidden:YES];
}



- (IBAction)FAMRecordButtonClick:(UIButton *)sender {
    WeakSelf(self);
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setValue:self.FAMCateType forKey:@"cate_type"];
    [parametersDic setValue:self.FAMFoodImageModel.image_key forKey:@"image_key"];
    [parametersDic setValue:[FAMUserManger shareInstance].FAMTimer forKey:@"fmt_date"];
    NSMutableArray *recordsArray = [NSMutableArray array];
    for (int i = 0; i<self.FAMFoodModel.foodList.count; i++) {
        FAMFoodIdentifyModel *model = self.FAMFoodModel.foodList[i];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:[[NSString nullToString:model.food_name] isEqualToString:@""] ? @"" : model.food_name forKey:@"food_name"];
        [dic setValue:model.weight forKey:@"weight"];
        [dic setValue:[[NSString stringWithFormat:@"%@", model.calories] isEqualToString:@""] ? @"0" : model.calories  forKey:@"calories"];
        [dic setValue:[[NSString stringWithFormat:@"%@", model.carbs] isEqualToString:@""] ? @"0" : model.carbs forKey:@"carbs"];
        [dic setValue:[[NSString stringWithFormat:@"%@", model.protein] isEqualToString:@""] ? @"0" : model.protein forKey:@"protein"];
        [dic setValue:[[NSString stringWithFormat:@"%@", model.fat] isEqualToString:@""] ? @"0" : model.fat forKey:@"fat"];
        [recordsArray addObject:dic];
    }
    [parametersDic setValue:recordsArray forKey:@"records"];
    __block FAMCameLoadingView *cameLoadingView = [[FAMCameLoadingView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:cameLoadingView];
    [FAMHttpTool FAM_PostFoodmateFoodRecordBatchWithParameters:[NSMutableDictionary dictionaryWithDictionary:@{@"data":parametersDic}] success:^(FAMFoodIdentifyModel * _Nonnull model, NSString * _Nonnull msg) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"FAMHomeLoadData" object:nil userInfo:nil];
            [cameLoadingView FAM_removeSelf];
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        });
    } failure:^(NSString * _Nonnull errorInfo) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [cameLoadingView FAM_removeSelf];
            [weakSelf showHint:errorInfo];
        });
    }];
}



@end
